//
//  ShakeQueryViewController.m
//  Patrol
//
//  Created by 范武 on 13-2-18.
//  Copyright (c) 2013年 FSTI. All rights reserved.
//

#import "ShakeQueryViewController.h"
#import "PatrolServiceClient.h"
#import "WorkListViewController.h"
#import "MBProgressHUD.h"
#import "FWAppDelegate.h"
#import "AudioToolbox/AudioToolbox.h"
#import "IOSAnalysisClient.h"

@interface ShakeQueryViewController ()
{
    BOOL haveShaked;
    
    BOOL locationServiceIsOpen;
    
    CLLocationManager * locationManager;
    
    CLLocationCoordinate2D locationCoordinate;
    
    SystemSoundID bellRing;
}
@end

@implementation ShakeQueryViewController


- (void)handleSearchForTerm:(NSString *)searchTerm {
    FWAppDelegate *appDelegate = (FWAppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *userName = appDelegate.userName;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = @"正在搜索...";
    NSInteger pageSize = 20;
    NSInteger pageNumber = 1;
    PatrolServiceClient * client = [PatrolServiceClient shareInstance];
    if (client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi || client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN){
        if (![searchTerm isEqualToString:@"*"]) {
            //操作统计
            [[IOSAnalysisClient sharedInstance] afterOperation:@{@"action_name" : kQueryTodoName, @"action_code" : kQueryTodoCode}];
            
            [client searchWithTerm:userName searchTerm:searchTerm resultBlock:^(id outJson, NSError *error){
                if (!outJson && error!=nil) {
                    DLog(@"Threre is somethings wrong ");
                    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                    [UIUtil alertOKWithTitle:@"错误" withMsg:@"网络错误" withDelegate:nil];
                    return ;
                }
                NSArray *workArray = outJson;
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                WorkListViewController *next = [[WorkListViewController alloc] initWithNibName:@"WorkListViewController" bundle:nil];
                next.title = @"维护作业列表";
                next.list = workArray;
                next.isPage = NO;
                [self.navigationController pushViewController:next animated:YES];
            }];
        }else{
            //操作统计
            [[IOSAnalysisClient sharedInstance] afterOperation:@{@"action_name" : kAllTodoName, @"action_code" : kAllTodoCode}];
            
            [client searchAll:userName pageSize:pageSize pageNumber:pageNumber resultBlock:^(id outJson, NSError *error) {
                if (!outJson && error!=nil) {
                    DLog(@"There is somethings wrong ");
                    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                    [UIUtil alertOKWithTitle:@"错误" withMsg:@"网络错误" withDelegate:nil];
                    return ;
                }
                NSDictionary *results = outJson;
                NSArray *workArray = [results objectForKey:@"list"];
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                WorkListViewController *next = [[WorkListViewController alloc] initWithNibName:@"WorkListViewController" bundle:nil];
                next.title = @"维护作业列表";
                next.list = workArray;
                next.allCount = [[results objectForKey:@"count"] integerValue];
                next.isPage = YES;
                [self.navigationController pushViewController:next animated:YES];
            }];
        }
    }else{
        [UIUtil alertOKWithTitle:@"错误" withMsg:@"当前没有连接任何网络" withDelegate:self];
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        return;
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        haveShaked = NO;
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    locationManager = [CLLocationManager new];
    
    NSString * path = [[NSBundle mainBundle] pathForResource:@"bell-ring" ofType:@"wav"];
    NSURL * wavUrl = [[NSURL alloc] initFileURLWithPath:path];
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)wavUrl, &bellRing);
    
    FWAppDelegate * delegate = (FWAppDelegate *)[[UIApplication sharedApplication] delegate];
    delegate.shakeQueryViewController = self;
    
    UITapGestureRecognizer * tapReco = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroudTap)];
    tapReco.delegate = self;
    [self.view addGestureRecognizer:tapReco];
    
    [_shakeBtn setBackgroundImage:[UIImage imageNamed:@"red btn"] forState:UIControlStateHighlighted];
}

#pragma mark - shake detective

-(BOOL) canBecomeFirstResponder
{
    return YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.view becomeFirstResponder];
    self.navigationController.navigationBarHidden = YES;
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.view resignFirstResponder];
    [super viewWillDisappear:animated];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (motion == UIEventSubtypeMotionShake) {
        DLog(@"mobile shaked!");
        [self onShake];
    }
}

- (void)backgroudTap
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:self forEvent:nil];
}

- (void)dealloc
{
    AudioServicesDisposeSystemSoundID(bellRing);
    
}

- (void)shakeAnimation
{
    [UIView animateWithDuration:0.1 animations:^{
        [_shakeBtn.po_frameBuilder moveWithOffsetX:5 offsetY:5];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            [_shakeBtn.po_frameBuilder moveWithOffsetX:-10 offsetY:-10];
        } completion:^(BOOL finished) {
           [UIView animateWithDuration:0.1 animations:^{
               [_shakeBtn.po_frameBuilder moveWithOffsetX:10 offsetY:10];
           } completion:^(BOOL finished) {
               [UIView animateWithDuration:0.1 animations:^{
                   [_shakeBtn.po_frameBuilder moveWithOffsetX:-5 offsetY:-5];
               }];
           }];
        }];
    }];
}

- (void)onShake
{
    
    AudioServicesPlaySystemSound(bellRing);
    [self shakeAnimation];
    
    haveShaked = YES;
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:self forEvent:nil];
    [self getLocation];
    if (locationServiceIsOpen) {
        if(locationCoordinate.longitude > 0.0 && locationCoordinate.latitude > 0.0){
            //操作统计
            [[IOSAnalysisClient sharedInstance] afterOperation:@{@"action_name" : kShakeTodoName, @"action_code" : kShakeTodoCode}];
            
            FWAppDelegate *appDelegate = (FWAppDelegate *)[UIApplication sharedApplication].delegate;
            appDelegate.latitude = locationCoordinate.latitude;
            appDelegate.longitude = locationCoordinate.longitude;
            NSString *userName = appDelegate.userName;
            [MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = @"正在搜索...";
            
            PatrolServiceClient * client = [PatrolServiceClient shareInstance];
            if (client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi || client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN) {
                [client searchWithGps:userName latitude:locationCoordinate.latitude longitude:locationCoordinate.longitude resultBlock:^(id outJson, NSError *error) {
                    if (!outJson && error!=nil) {
                        DLog(@"There is somethings wrong ");
                        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                        [UIUtil alertOKWithTitle:@"错误" withMsg:@"网络错误" withDelegate:nil];
                        return ;
                    }
                    NSArray *workArray = outJson;
                    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                    WorkListViewController *next = [[WorkListViewController alloc] initWithNibName:@"WorkListViewController" bundle:nil];
                    next.title = @"维护作业列表";
                    next.list = workArray;
                    next.isPage = NO;
                    [self.navigationController pushViewController:next animated:YES];
                }];
            }else{
                [UIUtil alertOKWithTitle:@"错误" withMsg:@"当前没有连接任何网络" withDelegate:self];
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                return;
            }
        }else{
            [UIUtil alertOKWithTitle:@"通知" withMsg:@"当前所在的位置无法获得GPS数据" withDelegate:nil];
        }
        
    }
}

- (void)getLocation
{
    if (![CLLocationManager locationServicesEnabled]) {
        locationServiceIsOpen = NO;
        UIAlertView * locationServiceDisableAlert = [[UIAlertView alloc] initWithTitle:@"通知" message:@"定位服务没打开，无法通过GPS来查询相关设备维护任务" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [locationServiceDisableAlert show];
    }else{
        locationServiceIsOpen = YES;
        [locationManager startUpdatingLocation];
        CLLocation * location = [locationManager location];
        locationCoordinate = location.coordinate;
        //        locationCoordinate.longitude = 118.608;
        //        locationCoordinate.latitude = 24.9012;
        DLog(@"longtitude: %f, latitude: %f",locationCoordinate.longitude, locationCoordinate.latitude);
        [locationManager stopUpdatingLocation];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma mark Search Bar Delegate Methods
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    _search.text = @"";
    [searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *searchTerm = [searchBar text];
    [searchBar resignFirstResponder];
    [self handleSearchForTerm:searchTerm];
}
- (void)viewDidUnload {
    [self setShakeBtn:nil];
    [super viewDidUnload];
}
- (IBAction)shakeBtnPress:(id)sender {
    [self onShake];
}
@end
